<?php
/**
 * WooCommerce My Account Edit Address Template
 * 地址管理页面模板，基于HTML模板 pro-address.html
 * 
 * @package WP Bootstrap Woo
 */

defined('ABSPATH') || exit;

$page_title = ($load_address === 'billing') ? esc_html__('Billing Address', 'woocommerce') : esc_html__('Shipping Address', 'woocommerce');
$address = WC()->countries->get_formatted_address($address);

?>

<!-- address section start -->
<div class="address-section">
    <div class="address-header">
        <h3><?php echo $page_title; ?></h3>
        <p>Update your <?php echo strtolower($page_title); ?> information</p>
    </div>
    
    <!-- address form -->
    <div class="address-form-wrap">
        <form method="post" class="edit-address-form">
            
            <div class="form-grid">
                <?php
                $fields = WC()->countries->get_address_fields(esc_attr($_GET['country'] ?? ''), $load_address . '_');
                
                foreach ($fields as $key => $field) :
                    $field_key = str_replace($load_address . '_', '', $key);
                    $field_value = wc_get_post_data_by_key($key, $address[$field_key] ?? '');
                    ?>
                    
                    <div class="form-group <?php echo esc_attr($field['class'][0] ?? 'form-row-wide'); ?>">
                        <?php woocommerce_form_field($key, $field, $field_value); ?>
                    </div>
                    
                <?php endforeach; ?>
            </div>
            
            <div class="address-actions">
                <button type="submit" class="btn-save-address" name="save_address" value="<?php esc_attr_e('Save address', 'woocommerce'); ?>">
                    <i class="feather-save"></i>
                    <span><?php esc_html_e('Save address', 'woocommerce'); ?></span>
                </button>
                
                <a href="<?php echo esc_url(wc_get_account_endpoint_url('edit-address')); ?>" class="btn-cancel">
                    <i class="feather-x"></i>
                    <span>Cancel</span>
                </a>
            </div>
            
            <?php wp_nonce_field('woocommerce-edit_address', 'woocommerce-edit-address-nonce'); ?>
            <input type="hidden" name="action" value="edit_address" />
        </form>
    </div>
</div>
<!-- address section end -->

<style>
.address-section {
    background: #fff;
    border-radius: 12px;
    padding: 30px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.address-header {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #dee2e6;
}

.address-header h3 {
    margin: 0 0 5px 0;
    color: #212529;
    font-weight: 600;
}

.address-header p {
    margin: 0;
    color: #6c757d;
}

.form-grid {
    display: grid;
    gap: 20px;
    margin-bottom: 30px;
}

.form-group {
    position: relative;
}

.form-group.form-row-wide {
    grid-column: 1 / -1;
}

.form-group.form-row-first,
.form-group.form-row-last {
    grid-column: span 1;
}

@media (min-width: 768px) {
    .form-grid {
        grid-template-columns: 1fr 1fr;
    }
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    color: #495057;
    font-weight: 500;
    font-size: 14px;
}

.form-group .required {
    color: #dc3545;
}

.form-group input,
.form-group select,
.form-group textarea {
    width: 100%;
    padding: 12px 15px;
    border: 2px solid #dee2e6;
    border-radius: 8px;
    font-size: 16px;
    transition: border-color 0.3s ease, box-shadow 0.3s ease;
    background: #fff;
    font-family: inherit;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
    outline: none;
    border-color: #007cba;
    box-shadow: 0 0 0 3px rgba(0, 124, 186, 0.1);
}

.form-group textarea {
    min-height: 100px;
    resize: vertical;
}

.form-group select {
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
    background-position: right 12px center;
    background-repeat: no-repeat;
    background-size: 16px;
    appearance: none;
    padding-right: 40px;
}

.form-group .woocommerce-input-wrapper {
    position: relative;
}

.form-group .description {
    font-size: 12px;
    color: #6c757d;
    margin-top: 5px;
    line-height: 1.4;
}

/* Validation styles */
.form-group input.invalid,
.form-group select.invalid,
.form-group textarea.invalid {
    border-color: #dc3545;
}

.form-group input.valid,
.form-group select.valid,
.form-group textarea.valid {
    border-color: #28a745;
}

.form-group .error-message {
    color: #dc3545;
    font-size: 12px;
    margin-top: 5px;
    display: none;
}

.form-group.has-error .error-message {
    display: block;
}

.address-actions {
    display: flex;
    gap: 15px;
    justify-content: flex-start;
    flex-wrap: wrap;
}

.btn-save-address,
.btn-cancel {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 12px 24px;
    border-radius: 8px;
    text-decoration: none;
    font-weight: 600;
    font-size: 14px;
    transition: all 0.3s ease;
    cursor: pointer;
    border: 2px solid;
    min-width: 140px;
    justify-content: center;
}

.btn-save-address {
    background: #007cba;
    color: #fff;
    border-color: #007cba;
}

.btn-save-address:hover {
    background: #005a8b;
    border-color: #005a8b;
    color: #fff;
}

.btn-cancel {
    background: #fff;
    color: #6c757d;
    border-color: #dee2e6;
}

.btn-cancel:hover {
    background: #f8f9fa;
    color: #495057;
    border-color: #adb5bd;
}

/* Loading state */
.btn-save-address.loading {
    position: relative;
    color: transparent;
}

.btn-save-address.loading::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 20px;
    height: 20px;
    border: 2px solid #fff;
    border-top: 2px solid transparent;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: translate(-50%, -50%) rotate(0deg); }
    100% { transform: translate(-50%, -50%) rotate(360deg); }
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .address-section {
        padding: 20px 15px;
    }
    
    .form-grid {
        grid-template-columns: 1fr;
    }
    
    .form-group.form-row-first,
    .form-group.form-row-last {
        grid-column: 1;
    }
    
    .address-actions {
        flex-direction: column;
    }
    
    .btn-save-address,
    .btn-cancel {
        width: 100%;
    }
}

/* Custom styling for country/state fields */
.form-group .select2-container {
    width: 100% !important;
}

.form-group .select2-selection {
    border: 2px solid #dee2e6 !important;
    border-radius: 8px !important;
    height: 48px !important;
    padding: 0 !important;
}

.form-group .select2-selection__rendered {
    padding: 12px 15px !important;
    line-height: 24px !important;
}

.form-group .select2-selection__arrow {
    height: 46px !important;
    right: 10px !important;
}

.form-group .select2-container--focus .select2-selection {
    border-color: #007cba !important;
    box-shadow: 0 0 0 3px rgba(0, 124, 186, 0.1) !important;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.querySelector('.edit-address-form');
    const submitBtn = document.querySelector('.btn-save-address');
    const requiredFields = form.querySelectorAll('input[required], select[required]');
    
    // Real-time validation
    requiredFields.forEach(field => {
        field.addEventListener('blur', validateField);
        field.addEventListener('input', clearValidationError);
    });
    
    // Form submission
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        if (validateForm()) {
            submitBtn.classList.add('loading');
            
            // Simulate form submission (replace with actual AJAX if needed)
            setTimeout(() => {
                form.submit();
            }, 1000);
        }
    });
    
    function validateField(e) {
        const field = e.target;
        const formGroup = field.closest('.form-group');
        const isRequired = field.hasAttribute('required');
        
        if (isRequired && !field.value.trim()) {
            showFieldError(formGroup, 'This field is required.');
            return false;
        }
        
        // Email validation
        if (field.type === 'email' && field.value) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(field.value)) {
                showFieldError(formGroup, 'Please enter a valid email address.');
                return false;
            }
        }
        
        // Phone validation
        if (field.name && field.name.includes('phone') && field.value) {
            const phoneRegex = /^[\+]?[1-9][\d]{0,15}$/;
            if (!phoneRegex.test(field.value.replace(/[\s\-\(\)]/g, ''))) {
                showFieldError(formGroup, 'Please enter a valid phone number.');
                return false;
            }
        }
        
        // Postal code validation
        if (field.name && field.name.includes('postcode') && field.value) {
            // Basic validation - can be enhanced based on country
            const postcodeRegex = /^[A-Za-z0-9\s\-]{3,10}$/;
            if (!postcodeRegex.test(field.value)) {
                showFieldError(formGroup, 'Please enter a valid postal code.');
                return false;
            }
        }
        
        clearFieldError(formGroup);
        field.classList.add('valid');
        return true;
    }
    
    function clearValidationError(e) {
        const field = e.target;
        const formGroup = field.closest('.form-group');
        
        if (field.classList.contains('invalid')) {
            field.classList.remove('invalid');
            clearFieldError(formGroup);
        }
    }
    
    function showFieldError(formGroup, message) {
        const field = formGroup.querySelector('input, select, textarea');
        const errorElement = formGroup.querySelector('.error-message') || document.createElement('div');
        
        field.classList.add('invalid');
        field.classList.remove('valid');
        
        errorElement.className = 'error-message';
        errorElement.textContent = message;
        
        if (!formGroup.querySelector('.error-message')) {
            formGroup.appendChild(errorElement);
        }
        
        formGroup.classList.add('has-error');
    }
    
    function clearFieldError(formGroup) {
        const field = formGroup.querySelector('input, select, textarea');
        const errorElement = formGroup.querySelector('.error-message');
        
        field.classList.remove('invalid');
        formGroup.classList.remove('has-error');
        
        if (errorElement) {
            errorElement.remove();
        }
    }
    
    function validateForm() {
        let isValid = true;
        
        requiredFields.forEach(field => {
            const formGroup = field.closest('.form-group');
            clearFieldError(formGroup);
            
            if (!field.value.trim()) {
                showFieldError(formGroup, 'This field is required.');
                isValid = false;
            } else if (!validateField({target: field})) {
                isValid = false;
            }
        });
        
        if (!isValid) {
            // Scroll to first error
            const firstError = form.querySelector('.has-error');
            if (firstError) {
                firstError.scrollIntoView({
                    behavior: 'smooth',
                    block: 'center'
                });
            }
        }
        
        return isValid;
    }
    
    // Auto-format phone number
    const phoneFields = form.querySelectorAll('input[name*="phone"]');
    phoneFields.forEach(field => {
        field.addEventListener('input', function(e) {
            let value = e.target.value.replace(/\D/g, '');
            if (value.length >= 10) {
                value = value.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
            }
            e.target.value = value;
        });
    });
    
    // Auto-format postal code
    const postcodeFields = form.querySelectorAll('input[name*="postcode"]');
    postcodeFields.forEach(field => {
        field.addEventListener('input', function(e) {
            e.target.value = e.target.value.toUpperCase();
        });
    });
});
</script>